<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-edit" :disabled="single" size="mini" @click="handleUpdate(ids[0])">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-delete" :disabled="multiple" size="mini"
          @click="handleDelete">删除</el-button></el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" icon="el-icon-download" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-upload2" size="mini" @click="handleImport" v-if="false">导入</el-button>
      </el-col>

      <el-form :model="queryParams" ref="queryDataRef" label-width="100px" :inline="true" class="el-form-search">
        <!--公司名称-->
        <el-form-item label="公司名称" prop="companyName" class="el-form-search-item">
          <el-input clearable placeholder="请输入公司名称" v-model.trim="queryParams.companyName"
            style="width: 140px"></el-input>
        </el-form-item>
        <!--联系人名称-->
        <el-form-item label="联系人名称" prop="contactName" class="el-form-search-item">
          <el-input clearable placeholder="输入联系人名称" v-model.trim="queryParams.contactName"
            style="width: 140px"></el-input>
        </el-form-item>
        <!-- 客户状态 -->
        <el-form-item label="客户状态" prop="isEnabled" class="el-form-search-item">
          <el-select v-model="queryParams.isEnabled" placeholder="客户状态">
            <el-option v-for="dict in customerStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table :height="tableHeight" :data="customerList" v-loading="loading" @selection-change="handleSelectionChange"
      border highlight-current-row>
      <el-table-column type="selection" width="50" align="center"></el-table-column>
      <el-table-column type="index" label="#" width="50" align="center">
        <template slot-scope="scope">
          {{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="公司名称" prop="companyName" show-overflow-tooltip width="120" align="center"
        :resizable="false"></el-table-column>
      <el-table-column label="联系人" prop="contactName" width="100" align="center" :resizable="false"></el-table-column>
      <el-table-column label="联系电话" prop="phone" width="100" align="center" :resizable="false"></el-table-column>
      <el-table-column label="电子邮件" prop="email" width="180" align="center" :resizable="false"></el-table-column>
      <el-table-column label="地区" prop="ancestorNames" width="240" align="center" :resizable="false"></el-table-column>
      <el-table-column label="地址" prop="address" width="240" align="center" :resizable="false"></el-table-column>
      <el-table-column label="状态" prop="isEnabled" width="100" align="center" :resizable="false">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.isEnabled == 0">
            <i class="el-icon-error"></i>
          </el-tag>
          <el-tag type="success" v-else-if="scope.row.isEnabled == 1">
            <i class="el-icon-success"></i>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="正式客户" prop="isFormalCust" width="100" align="center" :resizable="false">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.isFormalCust == 0">
            <i class="el-icon-error"></i>
          </el-tag>
          <el-tag type="success" v-else-if="scope.row.isFormalCust == 1">
            <i class="el-icon-success"></i>
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="服务日期" prop="serviceDate" width="100" align="center" :resizable="false">
        <template slot-scope="scope">
          {{ parseTime(scope.row.serviceDate, "{y}-{m}-{d}") }}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip
        :resizable="false"></el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row.num)">编辑</el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 修改/新增客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-dialogDrag width="800px" :close-on-click-modal="false">
      <el-form :model="formData" :rules="rules" ref="formDataRef" label-width="80px" @submit.prevent
        label-position="left">
        <!-- 第一行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input clearable placeholder="请输入公司名称" v-model.trim="formData.companyName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input clearable placeholder="请输入联系人" v-model.trim="formData.contactName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input clearable placeholder="请输入联系方式" v-model.trim="formData.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮件" prop="email">
              <el-input clearable placeholder="请输入电子邮件" v-model.trim="formData.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="服务日期" prop="serviceDate">
              <div class="el-p" style="width: 100%">
                <el-date-picker v-model="formData.serviceDate" type="date" placeholder="选择日期" style="width: 100%">
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="正式用户" prop="isFormalCust">
              <el-radio-group v-model="formData.isFormalCust">
                <el-radio :label="1">正式</el-radio>
                <el-radio :label="0">非正式</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <!--地区-->
            <el-form-item label="地区" prop="area">
              <treeselect v-model="formData.area" :options="areaOptions" :normalizer="normalizer" placeholder="选择地区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isEnabled">
              <el-radio-group v-model="formData.isEnabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第五行 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <!--地址-->
            <el-form-item label="地址" prop="address">
              <el-input clearable placeholder="请输入公司地址" type="textarea" :rows="2" :maxlength="100" resize="none"
                show-word-limit v-model.trim="formData.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第六行 -->
        <el-row :gutter="15">
          <el-col :span="24">
            <!--备注-->
            <el-form-item label="备注" prop="remark">
              <el-input clearable placeholder="请输入备注" type="textarea" :rows="2" :maxlength="100" resize="none"
                show-word-limit v-model.trim="formData.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormData">提交</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" v-dialogDrag
      :close-on-click-modal="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listCustomerALL,
  listCustomer,
  addCustomer,
  getCustomerByNum,
  updateCustomer,
  delCustomer,
} from "@/api/maintenance/customer";
import { listArea } from "@/api/maintenance/area";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
// 导入模板接口importTemplate
import { importTemplate } from "@/api/system/user";

export default {
  components: { Treeselect },
  data() {
    return {
      //遮罩层
      loading: true,

      /**头部导航栏参数 */
      // 单行
      single: true,
      // 多行
      multiple: true,
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        companyName: undefined,
        contactName: undefined,
        serviceDate: undefined,
        isEnabled: undefined,
        orderByColum: "update_time",
        isAsc: "asc",
      },

      /**表格参数 */
      // 表格的高度
      tableHeight: "calc(100vh - 200px)",
      // 表格列表
      customerList: [],
      // 总条数
      total: 0,
      // 勾选num集合
      ids: [],

      /**修改/新增对话框 */
      open: false,
      title: "",
      formData: {},
      // 地区数选项
      areaOptions: [],
      //校验规则
      rules: {
        companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" },
        ],
        // contactName: [
        //   { required: true, message: "联系人不能为空", trigger: "blur" },
        // ],
        // phone: [
        //   { required: true, message: "联系方式不能为空", trigger: "blur" },
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: "请输入正确的手机号码",
        //     trigger: "blur",
        //   },
        // ],
        email: [
          {
            type: "email",
            message: "请输入正确的电子邮箱",
            trigger: ["blur", "change"],
          },
        ],
        area: [{ required: true, message: "地区不能为空", trigger: "blur" }],
        isEnabled: [
          { required: true, message: "状态不能为空", trigger: "blur" },
        ],
      },
      customerStatusOptions: [],
      /**导入功能 */
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("customer_status").then((response) => {
      this.customerStatusOptions = response.data;
    });
  },
  methods: {
    /**查询客户列表 */
    getList() {
      this.loading = true;
      listCustomerALL(this.queryParams).then((response) => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**表单重置 */
    reset() {
      this.forData = {
        companyName: undefined,
        contactName: undefined,
        phone: undefined,
        email: undefined,
        area: undefined,
        address: undefined,
        isFormalCust: 0,
        isEnabled: 0,
      };
      this.resetForm("formDataRef");
      // 查询地区列表
      listArea().then((response) => {
        this.areaOptions = this.handleTree(
          response.data.filter((item) => item.num !== 1),
          "num"
        );
      });
    },
    /**新增客户 */
    handleAdd() {
      ``;
      this.reset();
      this.open = true;
      this.title = "新增客户";
    },
    /**修改客户 */
    handleUpdate(num) {
      this.reset();
      this.title = "修改客户";
      this.open = true;
      getCustomerByNum(num).then((response) => {
        this.formData = response.data;
      });
    },
    /**删除客户 */
    handleDelete(row) {
      let ids = row.num || this.ids;
      this.$modal
        .confirm(`确定删除吗`)
        .then(function () {
          delCustomer(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /**搜索 */
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**重置查询 */
    resetQuery() {
      this.resetForm("queryDataRef");
      this.handleSearch();
    },
    /**表格勾选回调 */
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.num);
      this.single = this.ids.length != 1;
      this.multiple = !this.ids.length;
    },
    /**提交新增/修改用户表单 */
    submitFormData() {
      this.$refs["formDataRef"].validate((valid) => {
        if (valid) {
          if (this.formData.num != undefined) {
            // 修改
            updateCustomer(this.formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            addCustomer(this.formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /**取消,关闭表单 */
    close() {
      this.resetForm("formDataRef");
      this.open = false;
    },
    /** 转换地区数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.num,
        label: node.name,
        children: node.children,
      };
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "zk/customer/export", //后端接口
        {
          ...this.queryParams, // 参数
        },
        `客户信息_${new Date().getTime()}.xlsx` //导出的文件名称
      );
    },

    /**导入功能 */
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "客户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },
};
</script>

<style>
/* :deep(.el-p .el-input__wrapper) {
  width: 100% !important;
} */
</style>
